package com.hongkzh.www.adv.service;

import com.google.common.collect.Lists;
import com.hongkzh.www.conmon.*;
import com.hongkzh.www.user.service.UserService;
import com.jfinal.aop.Before;
import com.jfinal.aop.Enhancer;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.activerecord.tx.Tx;

import java.util.*;

/**
 * @author martins
 */
public class AdvService extends BaseService {
    private static String imgSrc;


    public Page<Record> getRecommendList(int pageNumber) {
        SqlPara sqlPara = Db.getSqlPara("adv.getRecommendList");
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);

        for (Record r : records.getList()) {
            doFilePath(r);

        }
        return records;

    }

    public List<Record> getStaticList() {
        SqlPara sqlPara = Db.getSqlPara("adv.getStaticList");
        List<Record> records = Db.find(sqlPara);
        if (records == null) {
            records = Lists.newArrayList();
        }
        for (Record r : records) {
            doFilePath(r);

        }
        return records;

    }

    public List<Record> getCityAdvList() {
        SqlPara sqlPara = Db.getSqlPara("adv.getCityAdvList");
        List<Record> records = Db.find(sqlPara);
        if (records == null) {
            records = Lists.newArrayList();
        }


        return records;

    }

    public List<Record> getCityList() {
        SqlPara sqlPara = Db.getSqlPara("adv.getCityList");
        List<Record> records = Db.find(sqlPara);
        if (records == null) {
            records = Lists.newArrayList();
        }
        for (Record r : records) {
            doFilePath(r);
        }
        return records;

    }

    public List<Record> getMediaList() {
        SqlPara sqlPara = Db.getSqlPara("adv.getMediaList");
        List<Record> records = Db.find(sqlPara);
        if (records == null) {
            records = Lists.newArrayList();
        }
        for (Record r : records) {
            doFilePath(r);
        }
        return records;

    }

    public List<Record> getEnterpriseList() {
        SqlPara sqlPara = Db.getSqlPara("adv.getEnterpriseList");
        List<Record> records = Db.find(sqlPara);
        if (records == null) {
            records = Lists.newArrayList();
        }
        for (Record r : records) {

            doFilePath(r);
        }
        return records;

    }

    public List<Record> getTraditionList() {
        SqlPara sqlPara = Db.getSqlPara("adv.getTraditionList");
        List<Record> records = Db.find(sqlPara);
        if (records == null) {
            records = Lists.newArrayList();
        }
        for (Record r : records) {
            doFilePath(r);
        }
        return records;

    }

    public Page<Record> getHotAdvList(int pageNumber) {
        SqlPara sqlPara = Db.getSqlPara("adv.getHotAdvList");
        Page<Record> records = Db.paginate(pageNumber, StaticPublic.PAGESIZE, sqlPara);

        for (Record r : records.getList()) {
            doFilePath(r);
        }
        return records;

    }
    public Record getAdvByIdEx(String id) {
        SqlPara sqlPara = Db.getSqlPara("adv.getAdvByIdEx", id);
        Record r = Db.findFirst(sqlPara);
        if (r != null) {


            r.set("integral", 0);
          /*  if(null!=in){
                r.set("integral",in.getInt("integral"));
            }*/
//            r.set("imgSrc1", r.getStr("imgSrc"));
//            doFilePath(r);
//            r.set("imgSrc", r.getStr("imgSrc1"));
        }

        return r;

    }
    public Record getAdvById(String id, String userId) {
        SqlPara sqlPara = Db.getSqlPara("adv.getAdvById", id, userId);
        Record r = Db.findFirst(sqlPara);
        if (r != null) {
            r.set("collectionState", "0");
            if (StrKit.notBlank(r.getStr("collectionId"))) {
                r.set("collectionState", "1");
            }
            r.set("praiseState", "0");
            if (StrKit.notBlank(r.getStr("praiseId"))) {
                r.set("praiseState", "1");
            }
            //Record in= getAdvIntegralById(id,userId);
            r.set("integral", 0);
          /*  if(null!=in){
                r.set("integral",in.getInt("integral"));
            }*/
            r.set("imgSrc1", r.getStr("imgSrc"));
            doFilePath(r);
            r.set("imgSrc", r.getStr("imgSrc1"));
        }

        return r;

    }

    public Record getAdvIntegralById(String id) {
        SqlPara sqlPara = Db.getSqlPara("adv.getAdvIntegralByIdEx", id);
        Record r = Db.findFirst(sqlPara);
        return r;
    }
    public Record getAdvIntegralByIdEx(String id) {
        SqlPara sqlPara = Db.getSqlPara("enterprise.getAdvPlaySetById", id);
        Record r = Db.findFirst(sqlPara);
        return r;
    }
    public Record getAdvCommentsByCommentId(String commentId, String loginUid) {
        SqlPara sqlPara = Db.getSqlPara("adv.getAdvCommentsByCommentId", commentId, loginUid);
        Record record = Db.findFirst(sqlPara);
        doFilePath(record);
        doNumberPath(record);
        record.set("praiseState", "0");
        if (StrKit.notBlank(record.getStr("praiseId"))) {
            record.set("praiseState", "1");
        }
        record.set("createDate", DateUtil.CalculateTime(record.getStr("createDate")));
        return record;
    }

    public Page<Record> getAdvCommentsById(String id, int pageNumber, String loginUid) {
        SqlPara sqlPara = Db.getSqlPara("adv.getAdvCommentsById", id, loginUid);
        Page<Record> records = Db.paginate(pageNumber, 10, sqlPara);

        for (Record r : records.getList()) {
            doFilePath(r);
            doNumberPath(r);
            r.set("praiseState", "0");
            if (StrKit.notBlank(r.getStr("praiseId"))) {
                r.set("praiseState", "1");
            }
            r.set("createDate", DateUtil.CalculateTime(r.getStr("createDate")));
        }
        return records;

    }


    public List<Record> getAdvRecommendByAdvId(String id) {
        SqlPara sqlPara = Db.getSqlPara("adv.getAdvRecommendByAdvId", id, "2");
        List<Record> records = Db.find(sqlPara);
        for (Record r : records) {
            doFilePath(r);
        }
        return records;
    }

    public Map<String, List<Record>> getChinaList() {
        Map<String, List<Record>> map = new HashMap<>();
        List<Record> provinces = null, cities = null, areas = null;
        SqlPara sqlPara = null;
        if (!RedisTool.exists(StaticPublic.PROVINCES)) {
            sqlPara = Db.getSqlPara("adv.getProvinces");
            provinces = Db.find(sqlPara);
            if (null != provinces && provinces.size() > 0) {
                RedisTool.setexObject(StaticPublic.PROVINCES, StaticPublic.COUNTRYTIME, (provinces));
            }
        } else {
            provinces = (List<Record>) RedisTool.getObject(StaticPublic.PROVINCES);
        }
        map.put("provinces", provinces);

        if (!RedisTool.exists(StaticPublic.CITIES)) {
            sqlPara = Db.getSqlPara("adv.getCities");
            cities = Db.find(sqlPara);
            if (null != cities && cities.size() > 0) {
                RedisTool.setexObject(StaticPublic.CITIES, StaticPublic.COUNTRYTIME, (cities));
            }
        } else {
            cities = (List<Record>) RedisTool.getObject(StaticPublic.CITIES);
        }


        map.put("cities", cities);

        if (!RedisTool.exists(StaticPublic.AREAS)) {
            sqlPara = Db.getSqlPara("adv.getAreas");
            areas = Db.find(sqlPara);
            if (null != areas && areas.size() > 0) {
                RedisTool.setexObject(StaticPublic.AREAS, StaticPublic.COUNTRYTIME, (areas));
            }
        } else {
            areas = (List<Record>) RedisTool.getObject(StaticPublic.AREAS);
        }

        map.put("areas", areas);

        return map;
    }

    public List<Record> getCountryList() {
        SqlPara sqlPara = null;
        List<Record> countrys = null;
        if (!RedisTool.exists(StaticPublic.ALLCOUNTRY)) {
            sqlPara = Db.getSqlPara("adv.getCountryList");
            countrys = Db.find(sqlPara);
            if (null != countrys && countrys.size() > 0) {
                RedisTool.setexObject(StaticPublic.ALLCOUNTRY, StaticPublic.COUNTRYTIME, (countrys));
            }
        } else {
            countrys = (List<Record>) RedisTool.getObject(StaticPublic.ALLCOUNTRY);
        }
        return countrys;
    }

    public List<Record> getCountryStateList(String parentId) {
        String key = String.format(StaticPublic.COUNTRYSTATE, parentId);
        SqlPara sqlPara = null;
        List<Record> countrys = null;
        if (!RedisTool.exists(key)) {
            sqlPara = Db.getSqlPara("adv.getStateList", parentId);
            countrys = Db.find(sqlPara);
            if (null != countrys && countrys.size() > 0) {
                RedisTool.setexObject(key, StaticPublic.COUNTRYTIME, (countrys));
            }
        } else {
            countrys = (List<Record>) RedisTool.getObject(key);
        }
        return countrys;
    }

    /**
     * @param loginUid
     * @param id
     * @return
     */
    @Before(Tx.class)
    public Record endPlayEnterpriseAdvById(String loginUid, String Id) {

        Record re = new Record();
        re.set("type", 1);
        re.set("integral", 0);
        re.set("msg", "");
        Record advPlaySetRecord=  Db.findFirst(Db.getSqlPara("enterprise.getAdvPlaySetById", Id));
        if(advPlaySetRecord==null){
            return re;
        }

        String advId=advPlaySetRecord.getStr("sourceId");
        Db.update(Db.getSqlPara("enterprise.updatePlayCountData", advId));


        Record r4 = this.getAdvByIdEx(advId);
        String cid = IdGen.uuid();

        Record r2 = this.getAdvIntegralByIdEx(Id);
        UserService userService = Enhancer.enhance(UserService.class);
        if (null != r2 && r2.getInt("integralCount") > 0) {

            Record r = Db.findFirst(Db.getSqlPara("user.redHistoryByAdvIdByHotId", loginUid, Id));
            if (r != null) {
                return re;
            }

            String id = r2.getStr("id");
            int integralCount=r2.getInt("integralCount");
            int integral = r2.getInt("integral");
            re.set("integral", integral);
            re.set("type", r2.get("currencyType"));

            if ((integral > 0) && (integralCount>0)) {
                addRewordEx(r2, loginUid, "1",Id, advId);
            }
            userService.addRedPackLogEx(loginUid, integral, Id);

//            Db.update(Db.getSqlPara("media.updateEnterpriseHotAdvIntegral", advId));
            return re;
        } else {
            if (null != r4 && r4.getInt("integralCount") > 0) {

                Record r = Db.findFirst(Db.getSqlPara("user.redHistoryByAdvId", loginUid, advId));
                if (r != null) {
                    return re;
                }

                int integra = r4.getInt("integral");
                int integralCount=r2.getInt("integralCount");
                re.set("integral", integra);
                re.set("type", r4.get("currencyType"));
                if ((integra > 0) && (integralCount>0)) {
                    addRewordEx(r4, loginUid, "2",Id, advId);
                }
                userService.addRedPackLog(loginUid, integra, advId);
                return re;
            }
        }
        return re;
    }

    private void addRewordEx(Record r, String loginUid, String type, String Id,String advId) {
        int integra = r.getInt("integral");
//        int integralCount = r.getInt("integralCount");
        int i = 0;
        if (type.equals("1")) {
            i = Db.update(Db.getSqlPara("enterprise.updateAdvPlaySetIntegralCount", Id));
            i = Db.update(Db.getSqlPara("adv.updateHotIntegralCount", advId));

        } else {
            i = Db.update(Db.getSqlPara("adv.updateIntegralCount", advId));
        }
        if (i > 0) {
            Record userIntegralr = Db.findFirst(Db.getSqlPara("user.selectUserIntegral", loginUid));
            int userIntegral = userIntegralr.getInt("integral");

            Db.update(Db.getSql("user.insertUserIntegral"), IdGen.uuid(), loginUid, integra, 1, userIntegral + integra, "看广告");
            if (r.getStr("currencyType").equals("3")){
                Db.update(Db.getSqlPara("user.updateUserIntegral", integra, loginUid));
            }
            if (r.getStr("currencyType").equals("1")){
                Db.update(Db.getSqlPara("user.updateUserLeBeans", integra, loginUid));
            }
        }
    }

    private void addReword(Record r, String loginUid, String type, String advId) {
        int integra = r.getInt("integra");
        int i = 0;
        if (type.equals("1")) {
            i = Db.update(Db.getSqlPara("adv.updateHotIntegralCount", advId));
        } else {
            i = Db.update(Db.getSqlPara("adv.updateIntegralCount", advId));
        }
        if (i > 0) {
            Record userIntegralr = Db.findFirst(Db.getSqlPara("user.selectUserIntegral", loginUid));
            int userIntegral = userIntegralr.getInt("integral");

            Db.update(Db.getSql("user.insertUserIntegral"), IdGen.uuid(), loginUid, integra, 1, userIntegral + integra, "看广告");
            if (r.getStr("currencyType").equals("1")){
                Db.update(Db.getSqlPara("user.updateUserIntegral", integra, loginUid));
            }
            if (r.getStr("currencyType").equals("3")){
                Db.update(Db.getSqlPara("user.updateUserLeBeans", integra, loginUid));
            }

//            if (r.getStr("currencyType").equals("3")) {
//                Record userIntegralr = Db.findFirst(Db.getSqlPara("user.selectUserIntegral", loginUid));
//                int userIntegral = userIntegralr.getInt("integral");
//                Db.update(Db.getSqlPara("user.updateUserIntegral", integra, loginUid));
//
//                Db.update(Db.getSql("user.insertUserIntegral"), IdGen.uuid(), loginUid, integra, 1, userIntegral + integra, "看广告");
//            } else if (r.getStr("currencyType").equals("1")) {
//                Record r3 = Db.findFirst(Db.getSqlPara("game.getUserBean", loginUid));
//                if (r3 == null) {
//                    Db.update(Db.getSqlPara("game.saveUserBean", IdGen.uuid(), loginUid, integra));
//                } else {
//                    Db.update(Db.getSqlPara("game.updateUserBeanByUid", loginUid, integra));
//                }
//            }
        }
    }

    public Record historyEnterpriseAdv(String id, String loginUid) {
        SqlPara sqlPara = Db.getSqlPara("adv.historyEnterpriseAdv", id, loginUid, "2");
        return Db.findFirst(sqlPara);
    }

    public List<Record> getStaticListByType(String type) {
        SqlPara sqlPara = Db.getSqlPara("adv.getStaticListByType", type);
        List<Record> records = Db.find(sqlPara);
        if (records == null) {
            records = Lists.newArrayList();
        }
        for (Record r : records) {
            doFilePath(r);

        }
        return records;
    }


    @Before(Tx.class)
    public Record getRedPacketsMediaAdvById(String loginUid, String advId) {
        Record re = new Record();
        re.set("money", 0);
//        Record r = Db.findFirst(Db.getSqlPara("user.historyByAdvId", loginUid, advId));
        List<Record> list = Db.find(Db.getSqlPara("user.redHistoryByAdvId", loginUid, advId));
        if (list.size() > 0) {
            return re;
        }
        String key = "getRedPackets-" + advId;
        String requestId = IdGen.uuid();
        RedisTool.tryGetDistributedLock(key, requestId, 3);

        Record r = Db.findFirst(Db.getSqlPara("media.getRedPackets", advId));
        if (r == null) {
            return re;
        }
        String type = r.getStr("type");
        int money = r.getInt("money");
        int number = r.getInt("number");
        int totalMoney = r.getInt("totalMoney");

        UserService userService = Enhancer.enhance(UserService.class);
        if (type.equals("1")) {
            if (totalMoney < money) {
                return re;
            }
            re.set("money", money);
        } else {
            money = totalMoney / number;
            Random rand = new Random();
            money = rand.nextInt(money) + 1;
            money = money > totalMoney ? totalMoney : money;
            re.set("money", money);
        }
        Db.update(Db.getSqlPara("media.updateRedPackets", advId, money));
        userService.addIntegral(loginUid, money, "获得红包奖励");
        userService.addRedPackLog(loginUid, money, advId);
        RedisTool.releaseDistributedLock(key, requestId);
        return re;
    }


    @Before(Tx.class)
    public Record endPlayMediaAdvById(String loginUid, String advId) {
        {
            Db.update(Db.getSqlPara("enterprise.updatePlayCountData", advId));
            Record re = new Record();
            re.set("type", "0");

            Record r = Db.findFirst(Db.getSqlPara("user.historyByAdvId", loginUid, advId));
            if (r != null) {
                return re;
            }
            r = Db.findFirst(Db.getSqlPara("media.getRedPackets", advId));
            if (r != null) {
                re.set("type", "1");
            }
            r = Db.findFirst(Db.getSqlPara("media.getAdvById", advId, loginUid));
            String cid = IdGen.uuid();

            String sqlPara = Db.getSql("user.historyAdd");
            //用户历史记录
            Db.update(sqlPara, cid, loginUid, r.getStr("imgSrc"), r.getStr("imgRank"),
                    advId, r.getStr("title"), r.getStr("type"), r.getStr("coverImgSrc"));


            return re;
        }
    }

    public Page<Record> getInfoMediaAdvCommentReplyList(String commentId, int pageNumber) {
        SqlPara sqlPara = Db.getSqlPara("adv.getInfoMediaAdvCommentReplyList", commentId);
        Page<Record> records = Db.paginate(pageNumber, 10, sqlPara);

        for (Record r : records.getList()) {
            doFilePath(r);
            r.set("createDate", DateUtil.CalculateTime(r.getStr("createDate")));
        }
        return records;
    }

    @Before(Tx.class)
    public Record praiseMediaAdvComment(String commentId, String loginUid, int state) {
        if (state == 0) {

            int i = Db.update(Db.getSqlPara("adv.deletePraise", commentId, loginUid));
            if (i > 0) {
                Db.update(Db.getSqlPara("adv.reducePraisecount", commentId));
            }
        } else {

            try {
                Db.update(Db.getSqlPara("adv.savePraise", commentId, loginUid));
                Db.update(Db.getSqlPara("adv.addPraisecount", commentId));
            } catch (Exception e) {
                throw new BusinessException("已经点赞");
            }
        }

        Record record = Db.findFirst(Db.getSqlPara("adv.getPraisecount", commentId));
        doNumberPath(record);
        return record;
    }

    @Before(Tx.class)
    public void comment(String loginUid, String commentId, String ruserId, String content, String id) {
        if (StrKit.notBlank(commentId)) {
            Db.update(Db.getSqlPara("adv.saveMediaAdvCommentReply", IdGen.uuid(), commentId, loginUid, ruserId, content, id));
        } else {
            Db.update(Db.getSqlPara("adv.saveMediaAdvComment", IdGen.uuid(), id, loginUid, content));

        }
    }

    public List<Record> getUserHisTags(String loginUid) {
        return Db.find(Db.getSqlPara("adv.getUserHisTags", loginUid));

    }

    public List<Record> getRecommendTags() {
        return Db.find(Db.getSqlPara("adv.getRecommendTags"));
    }

    public List<Record> getCircles() {
        return Db.find(Db.getSqlPara("adv.getCircles"));
    }

    public List<Record> searchTags(String loginUid, String tag) {
        List<Record> allList = new ArrayList<>();
        List<Record> recommendTags = Db.find(Db.getSqlPara("adv.getRecommendTagBytag", tag));
        if (recommendTags != null && recommendTags.size() > 0) {
            allList.addAll(recommendTags);
        }
        List<Record> circles = Db.find(Db.getSqlPara("adv.getCirclesBytag", tag));
        if (circles != null && circles.size() > 0) {
            allList.addAll(circles);
        }
        return allList;
    }

    public Record getEnterpriseId(String enterpriseId, String loginUid) {
        Record r = Db.findFirst(Db.getSqlPara("adv.getEnterpriseId", enterpriseId, loginUid));
        r.set("followState", "0");
        if (StrKit.notBlank(r.getStr("followId"))) {
            r.set("followState", "1");
        }
        doImgPath(r);
        return r;
    }


    public List<Record> getAdvProductByAdvId(String id) {
        SqlPara sqlPara = Db.getSqlPara("shop.getAdvProductByAdvId", id);
        List<Record> records = Db.find(sqlPara);
        for (Record r : records) {
            doImgPath(r);
        }
        return records;
    }

    @Before(Tx.class)
    public void reportAdvById(String id, String loginUid) {
        Record record = Db.findFirst(Db.getSqlPara("adv.getUserAdvReport", loginUid, id));
        if (record != null) {
            throw new BusinessException("你已经举报了");
        }
        Db.update(Db.getSqlPara("adv.saveAdvReport", IdGen.uuid(), id, loginUid));
    }


}
